//
//  ReadBookVOrH_VC+Talk.m
//  KidReading
//
//  Created by telen on 16/3/8.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC+Talk.h"
#import "ConstDefine.h"
#import "NetDownTalk.h"

@interface ReadBookVOrH_VC ()<NetDownloadTalksDelegate,TalkVC_Delegate>
@end

@implementation ReadBookVOrH_VC (Talk)

+ (void)load
{
    [self swizzleSelector:@selector(viewDidLoad) withSelector:@selector(viewDidLoad_talk)];
    [self swizzleSelector:@selector(dealloc_My) withSelector:@selector(dealloc_talk)];
}

- (void)viewDidLoad_talk
{
    [self viewDidLoad_talk];
    //
    [[NetDownTalk shareSingle] unRegisterDownTalkStatusNotice:self];
    [[NetDownTalk shareSingle] registerDownTalkStatusNotice:self];
}

- (void)dealloc_talk
{
    [self dealloc_talk];
    //
    [[NetDownTalk shareSingle] unRegisterDownTalkStatusNotice:self];
}

- (void)readView_Accessibility_talkClicked
{
    //摄像头 麦克风判断
    if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            if (granted) {
                //NSLog(@"允许使用麦克风！");
                AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authorizationStatus == AVAuthorizationStatusRestricted) {
                    //无权限
                    //NSLog(@"受限");
                    [self showAlertMsg:@"Camera Limited" title:nil];
                }else if (authorizationStatus == AVAuthorizationStatusNotDetermined){
                    //NSLog(@"未决定");
                    AVCaptureDevice* camera = nil;
                    NSArray* devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
                    for(AVCaptureDevice* dev in devices){
                        if([dev position] == AVCaptureDevicePositionFront)
                        {
                            camera = dev;
                            break;
                        }
                    }
                    AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:camera error:nil];
                    input = nil;
                }else if (authorizationStatus == AVAuthorizationStatusDenied){
                    //NSLog(@"拒绝");
                    [self showAlertForCameraAndAudio:0];
                }else if (authorizationStatus == AVAuthorizationStatusAuthorized){
                    //NSLog(@"授权");
                    //
                    NSString* urlstr = self.talkInfo.talkZipUrl;
                    NSInteger talkid = self.talkInfo.talkId;
                    LongLong edition = self.talkInfo.edition;
                    NetworkStatus netstatus = [JRReachability reachabilityForLocalWiFi].currentReachabilityStatus;
                    if (netstatus == ReachableViaWiFi || [DataProcessing shareSingle].toContinueDown) {
                        [[NetDownTalk shareSingle] downTalkUrl:urlstr withTalkID:talkid edition:edition originalID:self.bookOid];
                    }else{
                        [[NetDownTalk shareSingle] checkDownTalkUrl:urlstr withTalkID:talkid edition:edition originalID:self.bookOid complete:^(BOOL isDone) {
                            if (isDone) {
                                [[NetDownTalk shareSingle] downTalkUrl:urlstr withTalkID:talkid edition:edition originalID:self.bookOid];
                            }else{
                                [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"nowifidownMSG") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
                                    if (buttonIndex == 1) {
                                        [[NetDownTalk shareSingle] downTalkUrl:urlstr withTalkID:talkid edition:edition originalID:self.bookOid];
                                        [DataProcessing shareSingle].toContinueDown = YES;
                                    }
                                } buttonTitles:ReadLocalizedString(@"cancel"),ReadLocalizedString(@"continuedown"),nil];
                            }
                        }];
                    }
                    //[readView.currentPageView.readFunctionPage setDownTalkProgress:0];
                }
            }
            else {
                //NSLog(@"不允许使用麦克风！");
                [self showAlertForCameraAndAudio:1];
            }
        }];
    }
    
    //statistical统计
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"我要说Talk"] needReturnValue:NO];
}

//MARK: UIAlertView Delegate
- (void)showAlertForCameraAndAudio:(int)index
{
    [UIAlertView tl_showTitle:nil message:ReadLocalizedString(@"talkCameraAndAudio") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            if ([[UIDevice currentDevice].systemVersion floatValue] < 8) {
                if (index == 1) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=MICROPHONE"]];
                }
                if (index == 0) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=CAMERA"]];
                }
            }else{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        }
    } buttonTitles:ReadLocalizedString(@"cancel"),ReadLocalizedString(@"sure"), nil];
}

//MARK: TalkDown
- (void)netDownloadTalkAllFinished:(NSInteger)originalid
{
    //NSLog(@"%@ %@->%@",NSStringFromSelector(_cmd),@(originalid),@(self.bookOid));
    if (self.bookOid == originalid) {
        [readView.currentPageView.readFunctionPage setDoneTalkProgress];
        if(readView.currentPageView.readFunctionPage.isClicedTalkBtn)[self openTalk];
    }
}

- (void)netDownloadTalkFilePercentage:(CGFloat)per originalID:(NSInteger)originalid
{
    //NSLog(@">>>>>>> %@",@(per));
    //NSLog(@"%@ %@->%@",NSStringFromSelector(_cmd),@(originalid),@(self.bookOid));
    if (per > 1)per = 1;
    if (self.bookOid == originalid) {
        [readView.currentPageView.readFunctionPage setDownTalkProgress:ceil(per*100.0)];
    }
}

- (void)netDownloadTalkFileFailed:(NSInteger)originalid
{
    //NSLog(@"%@ %@->%@",NSStringFromSelector(_cmd),@(originalid),@(self.bookOid));
    if (self.bookOid == originalid) {
        [[WaitingShow shareSingleShow] showString:ReadLocalizedString(@"talkDownFail") andAutoHide:YES];
        [readView.currentPageView.readFunctionPage setDoneTalkProgress];
    }
}


//MARK: Talk
- (void)openTalk
{
    //JR Project Data
    NSString* bookOid = @(self.bookOid).description;
    UIImage* bookCover = self.coverImg ? self.coverImg : readView.currentPageView.readFunctionPage.bookCoverImageView.image;
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    if (!uinfo || uinfo.uid == 0 || bookCover == nil) {
        return;
    }
    
    //JR Net Data
    NSString* jsonPath = [[DataProcessing talkPathForOriginalID:self.bookOid] stringByAppendingPathComponent:@"book.json"];
    NSString* json = [[NSString alloc] initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
    NSData* data = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error = nil;
    if (data == nil) {
        NSLog(@"BookJson Error: %@",error);
        return;
    }
    NSDictionary* talkInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if (error != nil) {
        NSLog(@"DebugError: %@",error);
        return;
    }
    
    NSArray* topic_timeArr = talkInfo[@"topic_time"];
    NSDictionary* topic1 = talkInfo[@"topic1"];
    NSDictionary* topic2 = talkInfo[@"topic2"];
    NSDictionary* topic3 = talkInfo[@"topic3"];
    if (!topic1 || !topic2 || !topic3 || !topic_timeArr || topic_timeArr.count != 4) {
        NSLog(@"BookJson Error");
        return;
    }
    
    //Talk Ref
    RecordingTimeInfo rinfo;
    rinfo.time_from = [topic_timeArr[0] integerValue];
    rinfo.pTime_1 = [topic_timeArr[1] integerValue];
    rinfo.pTime_2 = [topic_timeArr[2] integerValue];
    rinfo.time_to = [topic_timeArr[3] integerValue];
    
    //
    TalkViewController * vc = [[TalkViewController alloc] init];
    vc.saveVideoFullPath = [[DataProcessing talkInterviewViewSavePathForOriginalID:self.bookOid].path stringByAppendingPathComponent:[NSString stringWithFormat:@"talk_%@.mp4",bookOid]];
    vc.saveVideoFullPath_temp = [[DataProcessing talkInterviewViewSavePathForOriginalID:self.bookOid].path stringByAppendingPathComponent:[NSString stringWithFormat:@"talk_%@_rec.mp4",bookOid]];
    vc.saveVideoUploadedInfo = [[DataProcessing talkInterviewViewSavePathForOriginalID:self.bookOid].path stringByAppendingPathComponent:[NSString stringWithFormat:@"talk_%@_uploaded.plist",bookOid]];
    vc.isPhone = [DataProcessing shareSingle].deviceType == DevicesTypes_iPhone;
    vc.ratio = ratio_w;
    vc.coverImage = bookCover;
    vc.recordTimeInfo = rinfo;
    vc.q1 = topic1[@"topic_cn"];
    vc.q1_sub = topic1[@"topic_en"];
    vc.q2 = topic2[@"topic_cn"];;
    vc.q2_sub = topic2[@"topic_en"];
    vc.q3 = topic3[@"topic_cn"];;
    vc.q3_sub = topic3[@"topic_en"];
    vc.q1_mp4 = [[DataProcessing talkVideoPath] stringByAppendingPathComponent:topic1[@"video_url"]];
    vc.q2_mp4 = [[DataProcessing talkVideoPath] stringByAppendingPathComponent:topic2[@"video_url"]];
    vc.q3_mp4 = [[DataProcessing talkVideoPath] stringByAppendingPathComponent:topic3[@"video_url"]];
    
    //TalkFileRootPath
    vc.talkFileRoot = [DataProcessing talkVideoPath];
    
    vc.themeArr = @[];
    vc.currentTheme = [vc.themeArr firstObject];
    
    //UserInfo
    vc.uid = uinfo.uid;
    //vc.userNick = uinfo.userName;//TODO: nickName
    
    vc.bookSegmentFile = [[DataProcessing talkPathForOriginalID:self.bookOid] stringByAppendingPathComponent:@"book.json"];
    vc.run_out_XML_path = [[DataProcessing talkPathForOriginalID:self.bookOid] stringByAppendingPathComponent:@"end.json"];
    
    vc.delegate = self;
    
    [self presentViewController:vc animated:[DataProcessing shareSingle].canWindowRotation completion:nil];
}

- (BOOL)talkViewShareDefineMySelf:(UIView *)btnView withInfo:(NSDictionary *)dict
{
    
    //1、创建分享参数
    UIImage* imgtalk = [UIImage imageNamed:@"talk.jpg"];
    imgtalk = [imgtalk resizeImageWithNewSize:CGSizeMake(200, 200)];
    NSArray* imageArray = @[imgtalk];
    NSString* text = [NSString stringWithFormat:ReadLocalizedString(@"talkShareText"),self.bookName];
    NSString* title = @"Let's Talk - WaWaYaYa JoyReader";
    NSURL* url = dict[@"url"];
    
    if (imageArray) {
        [[ShareManager shareManager] JRShareWithText:text ImageArray:imageArray Url:url Title:title Type:SSDKContentTypeAuto BaseView:btnView statusChange:nil];
    }
    
    return YES;
}

- (void)talkViewUploadedSuccess_withInfo:(NSDictionary *)dict
{
#ifdef JReaderSDKControl
#else
    [[DataProcessing shareSingle] talkViewUploadedSuccess_Bookid:self.bookid withInfo:dict];
#endif
    
}

- (BOOL)talkViewShareEnable__ShareTo:(TalkShareTo_type)shareto
{
#ifdef JReaderSDKControl
    return NO;
#else
    if (shareto == TalkShareTo_wechat && ![WXApi isWXAppInstalled]) {
        return NO;
    }
    
    if (shareto == TalkShareTo_qq && ![QQApiInterface isQQInstalled]) {
        return NO;
    }
    return YES;
#endif
}

- (void)talkViewDidClicked_ShareTo:(TalkShareTo_type)shareto withInfo:(NSDictionary *)dict
{
#ifdef JReaderSDKControl
#else
    if (shareto == TalkShareTo_wechat && ![WXApi isWXAppInstalled]) {
        [self showAlertMsg:ReadLocalizedString(@"talkShareFailForWX") title:nil];
        return;
    }
    
    if (shareto == TalkShareTo_qq && ![QQApiInterface isQQInstalled]) {
        [self showAlertMsg:ReadLocalizedString(@"talkShareFailForQQ") title:nil];
        return;
    }
    
    [[DataProcessing shareSingle] talkViewDidClicked_ShareTo:shareto bookName:self.bookName withInfo:dict];
    
    //阅读统计
    [[DBHelper shareInstance] addReadInfo_talkOperation:self.bookid type:RType_share];
#endif
}

- (void)talkViewDidClicked_Play
{
    //阅读统计
    [[DBHelper shareInstance] addReadInfo_talkOperation:self.bookid type:RType_video];
}

@end
